// Outgoing message name must start with 'msg', incoming must end with 'Msg'.

package websocket

import (
	"json"
	"os"
	"bytes"
	"reflect"
)

type msgJoin struct {
	T string
	Nickname string
}

type joinResultMsg struct {
	T string
	Error string
}

func compose(msg interface{}) (data []byte, err os.Error) {
	var t string
	switch msg.(type) {
	case *joinResultMsg:
		t = "join_result"
	}
	reflect.ValueOf(msg).Elem().Field(0).SetString(t)
	data, err = json.Marshal(msg)
	return
}

func parse(data []byte) (msg interface{}, err os.Error) {
	buf := bytes.NewBuffer(data)
	t, err := buf.ReadString('{')
	if err != nil {
		return
	}
	i := len(t)-1
	// Strip the delimiter.
	switch t[:i] {
	case "join":
		msg = &msgJoin{}
	}
	println("Received:", string(data))
	err = json.Unmarshal(data[i:], msg)
	return
}
